/*
 * Copyright Thoughtworks, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.thoughtworks.go.apiv1.i18n;

import com.thoughtworks.go.api.base.OutputWriter;
import com.thoughtworks.go.spark.Routes;

import java.util.List;

public class I18nRepresenter {

    /**
     * 将 I18nData 转换为 JSON 格式（兼容旧版本）
     */
    public static void toJSON(OutputWriter jsonWriter, List<I18nItem> items, String locale, String page) {
        jsonWriter.addLinks(outputLinkWriter -> {
            outputLinkWriter.addLink("self", Routes.I18n.BASE + "?page=" + page + "&locale=" + locale);
            outputLinkWriter.addLink("doc", Routes.I18n.BASE + "/doc");
        });

        jsonWriter.addChild("_embedded", embeddedWriter -> {
            embeddedWriter.addChildList("items", itemsWriter -> {
                for (I18nItem item : items) {
                    itemsWriter.addChild(itemWriter -> {
                        itemWriter.addLinks(linkWriter -> {
                            linkWriter.addLink("self", Routes.I18n.BASE + "/" + page + "/" + locale + "/" + item.getId());
                        });
                        itemWriter.add("id", item.getId());
                        itemWriter.add("name", item.getName());
                        itemWriter.add("value", item.getValue());
                    });
                }
            });
        });
    }

    /**
     * 将 I18nData 转换为 JSON 格式（新版本，返回前端期望的格式）
     */
    public static void toJSON(OutputWriter jsonWriter, I18nData data, String locale) {
        // 返回前端期望的格式，包含 zh-CN 和 en 两种语言
        // 使用 addChild 来处理 Map 类型的数据
        jsonWriter.addChild("zh-CN", childWriter -> {
            data.getZhCN().forEach(childWriter::add);
        });

        jsonWriter.addChild("en", childWriter -> {
            data.getEn().forEach(childWriter::add);
        });
    }
}
